const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const retry = (fn, retries = 3, delay = 1000) => {
    return new Promise((resolve, reject) => {
        fn().then(resolve).catch((error) => {
            if (retries > 0) {
                return retry(fn, retries - 1, delay).then(resolve).catch(reject);
            }
            reject(error);
        });
    });
}
const pollingHanlder = (handler, delay=1000, maxTime=60000, immediate=true) => {
    // 当前轮询时间
    let currentWaitTime = 0;
    let timer = null;
    let stopType = false;
    // 获取轮询开始时间
    const startTime = new Date().getTime();
    return new Promise((resolve, reject) => {
        let result = null;
        // 停止轮询函数
        const stop = () => {
            stopType = true;
            clearTimeout(timer);
            resolve(result);
        };
        // 执行函数
        const excutor = () => {
            handler(stop).then(res => {
                result = res;
                return res;
            }).finally(() => {
                currentWaitTime = new Date().getTime() - startTime;
                // 判断轮询时间是否大于最大时间
                if(currentWaitTime >= maxTime){
                    reject(result);
                    return ;
                }
                // 判断是否已经停止
                if(stopType){
                    reject(result);
                    return ;
                }
                timer = setTimeout(() => {
                    excutor();
                }, delay);
            })
        }
        immediate? excutor(): setTimeout(() => {
            excutor();
        }, delay)
    })
}
module.exports = [
    wait,
    retry,
    pollingHanlder
]